var express = require('express');
var router = express.Router();
var http = require('client-http');
//var jquery = require('../public/javascripts/lib/jquery-1.12.0.js');
var config = require('../config.json');
var logger = require('log4js').getLogger();

/* GET home page.
 *
 * */
router.get('/', function (req, res, next) {

    if (req.session.user) {
        res.render('index', {title: 'SDP'});
    } else {
        var client_id = config.auth.client_id;
        var client_secret = config.auth.client_secret;
        var back_uri = config.auth.back_uri;
        var client_name = config.auth.client_name;
        var uc = config.auth.uc;

        res.redirect(uc+'/oauth/authLogin?client_id=' + client_id + '&client_secret=' + client_secret + '&back_uri=' + back_uri);
    }

});

router.get('/auth', function (req, res) {
    var code = req.query.code;
    http.request(config.auth.uc_private + config.auth.token_path, function (data) {
        var dataJson = JSON.parse(data);
        var access_token = dataJson.access_token;
        http.get(config.auth.uc_private + config.auth.user_path + '?access_token=' + access_token, function (user_data) {
            var userJson = JSON.parse(user_data);
            req.session.user = userJson.user;

            res.redirect('/');
        });
    }, "grant_type=authorization_code&client_id=" + config.auth.client_id + "&client_secret=" + config.auth.client_secret + "&code=" + code, {"Content-Type": "application/x-www-form-urlencoded"});
});

router.get('/session', function(req, res, next){
        req.session.destroy(function (err) {
            res.clearCookie("cur_project");
            res.redirect('/');
        });
});
router.get('/project_manage', function(req, res, next){
    if (req.session.user) {
        res.render("project_manage", {
            shortid:req.session.user.shortid,
            username: req.session.user.loginname,
            avatar: req.session.user.avatar_src,
            title:"SDP"
        });
    } else {
        var client_id = config.auth.client_id;
        var client_secret = config.auth.client_secret;
        var back_uri = config.auth.back_uri;
        var client_name = config.auth.client_name;
        var uc = config.auth.uc;
        res.redirect(uc+'/oauth/authLogin?client_id=' + client_id + '&client_secret=' + client_secret + '&back_uri=' + back_uri);
    }
});

router.get('/dataSource', function (req, res) {

    var datasource = require('../datasource.json').datasources;
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.json(datasource);
});

module.exports = router;
